package com.jack.tang.netty.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class NIOSocket {
    public static void main(String[] args) throws IOException
    {
        ServerSocketChannel open = ServerSocketChannel.open();
        open.socket().bind(new InetSocketAddress(8089));
        open.configureBlocking(false);
        Selector selector = Selector.open();
        open.register(selector, SelectionKey.OP_ACCEPT);

        while (true) {

            selector.select();
            for (SelectionKey selectionKey : selector.selectedKeys()) {
                if (selectionKey.isAcceptable()) {
                    ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel();
                    serverSocketChannel.accept();
                    serverSocketChannel.configureBlocking(false);
                    serverSocketChannel.register(selector, SelectionKey.OP_READ);
                    System.out.println("accept");
                }
                if (selectionKey.isReadable()) {
                    SocketChannel channel = (SocketChannel) selectionKey.channel();
                    ByteBuffer allocate = ByteBuffer.allocate(1024);
                    int read = channel.read(allocate);
                    if (read == -1){
                        channel.close();
                    }else if (read > 0) {
                        allocate.flip();
                        System.out.println(new String(allocate.array()));
                    }
                    System.out.println("read");
                }
            }
        }
    }
}
